<?php
/*
 * 商品管理
 */
namespace Admin\Controller;
use Admin\Model\goodsModel;
use Admin\Model\goodstypeModel;
use Admin\Model\goodsguigeModel;
use Admin\Model\memberModel;

class GoodsController extends BaseController {
    
    public $goodsModel;
    public $goodstypeModel;
    public $goodsguigeModel;
    
    public function __construct() {
        parent::__construct();
        $this->goodsModel = new goodsModel();
        $this->goodstypeModel = new goodstypeModel();
        $this->goodsguigeModel = new goodsguigeModel();
        
        $this->_get_gtype();//获取商品分类
    }
    
    protected function _get_goods_where(){
        $arrow = array(
            "goods_name","ischeck","gtype_id","is_tejia","is_new","is_hot","is_zhekou"
        );//允许提交的数据
        $data = param_filter($_GET,$arrow,$must=NULL,$filter=true);//过滤数据
        
        $where = "1";
        //todo
        if(is_set($data,'goods_name')){
            $where .= " AND goods_name like '%".$data['goods_name']."%'";
        }
        
        if(is_set($data,'gtype_id')){
            $where .= " AND gtype_id =".$data['gtype_id'];
        }
        
        if(is_set($data,'is_tejia')){
            $where .= " AND is_tejia =".$data['is_tejia'];
        }
        
        if(is_set($data,'is_new')){
            $where .= " AND is_new =".$data['is_new'];
        }
        
        if(is_set($data,'is_hot')){
            $where .= " AND is_hot =".$data['is_hot'];
        }
        if(is_set($data,'is_zhekou')){
            $where .= " AND is_zhekou =".$data['is_zhekou'];
        }
        
        
        return $where;
    }
    
    /*
     * 统计商品数量
     */
    protected function _get_goods_count(){
        $where = $this->_get_goods_where();//不带status的查询条件
        //全部订单
        //0全部,1出售中,2售空,3下架
        $goods_count =  array();
        $goods_count[0] = $this->goodsModel->getGoodsCount($where);//
        $goods_count[1] = $this->goodsModel->getGoodsCount($where." AND ischeck=1");//
        $goods_count[2] = $this->goodsModel->getGoodsCount($where." AND stock=0");//
        $goods_count[3] = $this->goodsModel->getGoodsCount($where." AND ischeck=0");

        return $goods_count;
    }
    
    /*
     * 删除
     */
    public function del(){
        
        $id = get("id");
        $where = array(
            "goods_id" => $id
        );
    
        $res = $this->goodsModel->where($where)->delete();
        if($res){
            return_json(0,"删除成功");
        }
        return_json(1,"删除失败");
    
    }
    
    
    /*
     * 商品列表
     */
    public function index(){
        $page = get('p',1);
        $where = $this->_get_goods_where();
        if(is_set($_GET,'ischeck')){
            $where .= " AND ischeck = '".get('ischeck')."'";
        }
        //统计数量
        $goods_count = $this->_get_goods_count();
        $this->assign('goods_count',$goods_count);

        $goods_list = $this->goodsModel->getGoodsList($where,$page);
        $this->assign('datalist',$goods_list);
        $this->display();
    }
    
    
    /*
     * 出售中的的商品
     */
    public function onsale(){
        $page = get('p',1);
        $where = $this->_get_goods_where();
        $where .= " AND ischeck = 1";
    
        //统计数量
        $goods_count = $this->_get_goods_count();
        $this->assign('goods_count',$goods_count);
        
        $goods_list = $this->goodsModel->getGoodsList($where,$page);
        $this->assign('datalist',$goods_list);
        $this->display('index');
    }
    
    /*
     * 仓库中的的商品
     */
    public function onsku(){
        $page = get('p',1);
        $where = $this->_get_goods_where();
        $where .= " AND ischeck = 0";

        //统计数量
        $goods_count = $this->_get_goods_count();
        $this->assign('goods_count',$goods_count);
        
        $goods_list = $this->goodsModel->getGoodsList($where,$page);
        $this->assign('datalist',$goods_list);
        $this->display('index');
    }
    
    /*
     * 卖完的的商品
     */
    public function outstock(){
        $page = get('p',1);
        $where = $this->_get_goods_where();
        $where .= " AND stock = 0";

        //统计数量
        $goods_count = $this->_get_goods_count();
        $this->assign('goods_count',$goods_count);
        
        $goods_list = $this->goodsModel->getGoodsList($where,$page);
        $this->assign('datalist',$goods_list);
        $this->display('index');
    }
    
    /*
     * 添加商品图片
     */
    public function uploadpic(){
        
        if(empty($_FILES)){
            return_json(1,"请上传图片");
        }
        
        $res = $this->iupload("goods");//上传操作
        //上传失败
        if(empty($res)){
            return_json(1,"上传失败,请重新上传");
        }
        
        return_json(0,"上传完毕",$res);
    }
    
    /*供货价格*/
    public function gonghuoMoney(){
        if(!IS_AJAX){
            return_json(1,"系统错误");
        }
        
        $gonghuo_price = post('gonghuo_price');
        $gonghuo_uid = post('gonghuo_uid');
        
        $memberModel = new memberModel();
        $gonghuo = $memberModel->getMember(array('uid'=>$gonghuo_uid));
        if(empty($gonghuo)){
            return_json(1,"请填写供货商用户编号uid");
        }
        
        
        $goods_id = get("goods_id");
        $where = array(
            "goods_id" => $goods_id,
        );
        $data = array(
            "gonghuo_price" => $gonghuo_price,
            "gonghuo_uid" => $gonghuo_uid,
            "gonghuo_realname" => $gonghuo['realname'],
        );
        $res = $this->goodsModel->editGoods($where, $data);
        if($res !== false){
            return_json(0,"已保存",'','/admin/goods/supplier');
        }
        return_json(1,"系统错误");
    }
    

    /*
     * add goods
     */
    public function addGoods(){
		
        if(!IS_AJAX){
            return_json(1,"系统错误");
        }
        
        $goods_id = get("goods_id");

        $arrow = array(
            "goods_name","market_price","shop_price","stock",
            "unit","sale_basic","brokerage_percent","brokerage_money",
            "directly_rate","superior_rate",
            "three_rate","four_rate","five_rate","six_rate",
            "is_fx_commission","is_shiwu",
            "freight_payer","ischeck",
            "ord","gtype_id","shipping",
            "vote_nums","goods_thumb",
            "is_cart","buy_text","is_xuanfu",
            "is_vote","is_idcard","is_imei",
            "min_buy","max_buy","double_buy","score_rate",
            "is_tejia","is_new","is_hot","is_zhekou","goods_weight",
            "goods_bianhao","gonghuo_price","ceo_price","king_price",
            "grade1_price","grade2_price","grade3_price","grade4_price","grade5_price",
            "grade6_price","grade7_price","grade8_price","month_imgurl","hot_imgurl",'video_thumb',
            'grade7_prize','grade8_prize','grade_id','is_grade3','is_grade4','yongjin_times',"desc1","desc2"
        );
        $goods_data = param_filter($_POST,$arrow,false,true);
        if($goods_data['yongjin_times']<=0){
            return_json(1,"佣金倍数至少为1");
        }

        if(empty($goods_data['goods_name'])){
            return_json(1,"请填写商品名称");
        }
        
        $goods_thumb = $_POST["goods_thumb"];
         
        if(empty($goods_thumb)){
            return_json(1,"请上传商品图片");
        }
        $goods_data['grade1_price'] = $goods_data['grade2_price'] = $goods_data['grade3_price'] = 
        $goods_data['grade4_price'] = $goods_data['grade5_price'] = $goods_data['grade6_price'] =$goods_data['grade7_price']= $goods_data['shop_price'];

        $goods_data['goods_pic'] = current($goods_thumb);//商品主图
        $goods_data['goods_thumb'] = json_encode($goods_thumb);//把数组拼接成字符串
        
        if($goods_data['shop_price']<0.01){
            //return_json(1,"商品价格设置不正确");
        }
        if($goods_data['stock']<1){
            $goods_data['stock'] = 1;
        }
        
        if($goods_data['min_buy']<1){
            $goods_data['min_buy'] = 1;
        }
        
        if($goods_data['max_buy']<1){
            $goods_data['max_buy'] = 999999999;
        }
        
        if($goods_data['double_buy']<1){
            $goods_data['min_buy'] = 1;
        }
        
        if($goods_data['max_buy'] < $goods_data['min_buy']){
            return_json(1,"最大购买数必须大于最小购买数");
        }
        
        if($goods_data['double_buy'] >1){
            
            if($goods_data['max_buy']<$goods_data['double_buy']){
                return_json(1,"最大购买数必须大于倍数");
            }
            
        }
        
        if($goods_data['brokerage_money']>$goods_data['shop_price']){
            //return_json(1,"商品PV必须小于商品售价");
        }
        
       

        //检查规格
        $guige = $_POST["guige"];
        $new_guige = array();
        
        if(!empty($guige)){
            //过滤掉空值
            foreach($guige as $k=>$v){
                $guige_v = htmlspecialchars(trim($v));//过滤数据
                if($guige_v){
                    $new_guige[$k] =  array(
                        "size_id" => $k,
                        "guige_size" => $guige_v,
                        "guige_price" => $goods_data['shop_price'],
                        "guige_stock" => $goods_data['stock'],
                        "guige_type" => 1,
                        "ord" => $k
                    );//赋值
                    if($goods_id){
                        $new_guige[$k]["goods_id"] = $goods_id;
                    }
                    
                }
            }
        }
    
        $new_xx = array();
        $xx = $_POST['xx'];
        if ($xx) {
            foreach ($xx as $key => $x) {
                if (!empty($x)) {
                    //过滤掉空值
                    foreach ($x as $k => $x) {
                        $guige_v = htmlspecialchars(trim($x)); //过滤数据
                        if ($guige_v) {

                            $new_xx[$key][] = $guige_v;
                        }
                    }
                }
            }
            $goods_data['guige_new'] = serialize($new_xx);
        } else {
            $goods_data['guige_new'] = '';
        }
        //规格的名字
        $guige_names = $_POST["guige_names"];
        if ($guige_names) {
            $goods_data['guige_names'] = serialize($guige_names);
        } else {
            $goods_data['guige_names'] = '';
        }

        if($goods_id){
            //编辑
            $goods_data['sale_all'] = $goods_data['sale_basic'] + $goods_data['sale_real'];//总的销量,包含假数据

            $where = array(
                "goods_id" => $goods_id
            );
            $res = $this->goodsModel->editGoods($where,$goods_data);
            
            if($res !== false){
                //更新规格
                if(empty($new_guige)){
                    //清除规格数据
                    $this->goodsguigeModel->where($where)->delete();
                }else{
                    //有规格,更新规格

                    //逐个更新
                    $new_id = array();
                    foreach($new_guige as $k=>$v){
                        //查找数据
                        $res = $this->goodsguigeModel->getGoodsguige(array("guige_size"=>$v['guige_size']));
                        if($res){
                            //有, 更新
                            $this->goodsguigeModel->editGoodsguige(array("guige_id"=>$res['guige_id']), $v);//更新数据
                            $new_id[] = $res['guige_id'];
                        }else{
                            //无添加
                            $res_id = $this->goodsguigeModel->addGoodsguige($v);//添加数据
                            $new_id[] = $res_id;
                        }
                    }
                    
                 //   pr($new_id);
                    
                    //删除多余的
                    $where_del = array(
                        "guige_id" => array("NOT IN",$new_id),
                        "goods_id" => $goods_id
                    );
                    
                    $this->goodsguigeModel->where($where_del)->delete();
                  // echo $this->goodsguigeModel->getLastSql();
                    
                }

                return_json(0,"编辑商品信息成功","","/admin/goods/editdetail/?goods_id=".$goods_id);
            }
        }else{
            //新增
            $goods_data['create_time'] = date("Y-m-d H:i:s");//创建时间
            $goods_data['sale_all'] = $goods_data['sale_basic'];//总的销量,包含假数据
            
            //添加商品信息到数据库
            $goods_id = $this->goodsModel->addGoods($goods_data);
            if($goods_id){
                
                if(!empty($new_guige)){
                    //有规格,添加规格数据
                    foreach($new_guige as $k=>$v){
                        $new_guige[$k]['goods_id'] = $goods_id;//添加商品id
                    }
                    $this->goodsguigeModel->addAll($new_guige);
                }
                
                return_json(0,"编辑商品信息成功","","/admin/goods/editdetail/?goods_id=".$goods_id);
            }
        }
        
        return_json(1,"添加商品失败");
        
    }
    
    
    /*
     * 获取商品分类
     */
    public function _get_gtype(){
        $data = $this->goodstypeModel->getGoodstypeList();
        $gtypes = array();
        foreach($data as $k=>$v){
            $gtypes[$v['gtype_id']] = $v;
        }
        $this->assign('gtype',$gtypes);
        return $data;
    }
    
    
    /*
     * 添加商品
     */
    public function add(){
        $gradeList = M('grade')->order('grade_id')->select();
        $this->assign('gradeList',$gradeList);
        $this->display('edit');
    }
    
    /*
     * 编辑商品
     */
    public function edit(){
        $goods_id = get("goods_id");
        $where  = array(
            "goods_id" => $goods_id
        );
        $goods = $this->goodsModel->getGoods($where);
        if(empty($goods_id)){
            $this->error("该商品不存在","/admin/goods/index");exit;
        }
        
        //获取商品规格
        $guige = $this->goodsguigeModel->getGoodsguigeLists($where);
        $goods['guige'] = $guige;
        
        //jinjianghai  test
        $guige_new = unserialize($goods['guige_new']);
        $this->assign('guige_new',$guige_new);
        $guige_names = unserialize($goods['guige_names']);
        $this->assign('guige_names',$guige_names);
        $this->assign("goods",$goods);
        
        $gradeList = M('grade')->where('grade_id!=1')->order('grade_id')->select();
        $this->assign('gradeList',$gradeList);
        $this->display();
    }
    
    
    /*
     * 编辑详情
     */
    public function editdetail(){
        
        $goods_id = get("goods_id");
        $where  = array(
            "goods_id" => $goods_id
        );
        
        if(IS_AJAX){

            $allow = $must = array("goods_desc");
            $data = param_filter($_POST, $allow,$must,FALSE);
            if(empty($goods_id)){
                return_json(1,"商品参数错误");
            }
            if(empty($data)){
                return_json(1,"商品详情不能为空");
            }

            $res = $this->goodsModel->editGoods($where, $data);
            if($res !== false){
                return_json(0,"编辑商品详情成功");
            }
            return_json(1,"编辑商品出错");
        }
        

        $goods = $this->goodsModel->getGoods($where);
        if(empty($goods_id)){
            $this->error("该商品不存在","/admin/goods/index");exit;
        }
        $goods['goods_desc'] = stripslashes($goods['goods_desc']);
        $this->assign("goods",$goods);

        $this->display();
    }
    

    
    


    /*
     * 商品分类
     */
    public function fenlei(){
        //$fenlei = $this->_get_gtype();
        $this->display();
    }
    
    /*
     * 编辑分类
     */
    public function edittype(){
         

        if(IS_POST){
            $gid = get("gtype_id");
            $data = array(
                "gtype_name" => get("gtype_name"),
                "gtype_ord" => get("gtype_ord")
            );
    
            $pic = $this->iupload("goodstype");
            if($pic){
                $data['gtype_icon'] = $pic['pic']['savepath'].$pic['pic']['savename'];
            }
            
            
            if($gid){
                $res = $this->goodstypeModel->where(array("gtype_id"=>$gid))->save($data);
                if($res !== false){
                    $this->redirect('/admin/goods/fenlei');
                }
            }else{
                $res = $this->goodstypeModel->add($data);
                if($res){
                    $this->redirect('/admin/goods/fenlei');
                }
            }
    
            $this->redirect('/admin/goods/fenlei');
    
        }
    
        $id = get("id");
        $res = $this->goodstypeModel->where(array("gtype_id"=>$id))->find();
        $this->assign("data",$res);
         
        $this->display();
    }
    
    public function deltype(){
        $id = get("id");
        if($id){
            $res = $this->goodstypeModel->where(array("gtype_id"=>$id))->delete();
            if($res){
                return_json(0,"删除成功","","/admin/goods/fenlei");
            }
        }
        return_json(1,"删除失败");
    }
    
       
    /*
     * 供应商编辑页面
     */
    /*
     * 商品列表
     */
    public function supplier(){
        $page = get('p',1);
        $where = $this->_get_goods_where();
        if(is_set($_GET,'ischeck')){
            $where .= " AND ischeck = '".get('ischeck')."'";
        }
        //统计数量
        $goods_count = $this->_get_goods_count();
        $this->assign('goods_count',$goods_count);

        $goods_list = $this->goodsModel->getGoodsList($where,$page);
        $this->assign('datalist',$goods_list);
        $this->display();
    }
    /*
     * 编辑商品
     */
    public function supplieredit(){
        $goods_id = get("goods_id");
        $where  = array(
            "goods_id" => $goods_id
        );
        $goods = $this->goodsModel->getGoods($where);
        if(empty($goods_id)){
            $this->error("该商品不存在","/admin/goods/index");exit;
        }
    
        //获取商品规格
        $guige = $this->goodsguigeModel->getGoodsguigeLists($where);
        $goods['guige'] = $guige;
    
        //jinjianghai  test
        $guige_new = unserialize($goods['guige_new']);
        $this->assign('guige_new',$guige_new);
    
        $this->assign("goods",$goods);
        $this->display();
    }
    
    
    
}